package com.vf.admin.common.freemarker;

import com.vf.admin.utils.HtmlRegexpUtil;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;
@Component
public class HtmlGuolv implements TemplateDirectiveModel {

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {

        String html = "";
        int length = 0;
        if (params != null && params.get("html") != null) {
            html = "" + params.get("html");
        }
        html = htmlspecialcharsFan(html);
        html = html.replaceAll("</?[^<>]*>", "");
        length = Integer.valueOf("" + params.get("length"));

        StringBuffer bf = new StringBuffer();// 用于追加子串
        char[] chars = html.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] > 127) {
                // 汉字是两个字节,判断汉字可以如下:第一个字节大于127并且第二个字节也
                // 大于127,则是汉字,否则不是.
                // System.out.println(chars[i] + "---ASCII--- " +
                // Integer.toHexString(chars[i])); //可以打印出ASCII码
//				System.out.println(chars[i]);
                bf.append(chars[i]);
            }
        }
//		System.out.println(bf.toString());
        String htmlstr = "";
        if(bf.length()>length){
            htmlstr = bf.substring(0, length);
        }else{
            htmlstr = bf.toString();
        }

        // 真正开始处理输出内容
        Writer out = env.getOut();
        out.write(HtmlRegexpUtil.filterHtml(htmlstr));
    }

    private String htmlspecialcharsFan(String str) {
        str = str.replaceAll("&amp;", "&");
        str = str.replaceAll("&lt;", "<");
        str = str.replaceAll("&gt;", ">");
        str = str.replaceAll("&quot;", "\"");
        return str;
    }

}
